package main.java.indi.zyj.coderecord;

public class NumEnclaves {

    public int numEnclaves(int[][] grid) {

        int l = grid.length;;
        int m = grid[0].length;

        for (int i = 0; i < l; i++) {
            dfs(grid, i, 0);
            dfs(grid, i, m - 1);
        }
        for (int i = 0; i < m; i++) {
            dfs(grid,0, i);
            dfs(grid,l - 1, i);
        }

        int res = 0;
        for (int i = 0; i < l; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 1)
                    res++;
            }
        }
        return res;
    }
    public void dfs(int[][] grid, int i, int j){
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0)
            return;
        grid[i][j] = 0;
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }

}
